<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>我的订单 - 美味外卖</title>
		<link rel="stylesheet" href="css/orders.css">
		<script src="js/jquery-3.7.1.js"></script>
	</head>
	<body>
		<!-- 顶部标题栏 -->
		<div class="header">
			<div class="back-btn" onclick="goBack()">←</div>
			<div>我的订单</div>
		</div>

		<!-- 订单状态标签 -->
		<div class="order-tabs">
			<div class="tab active" onclick="switchTab('all')">全部</div>
			<div class="tab" onclick="switchTab('pending_payment')">待付款</div>
			<div class="tab" onclick="switchTab('pending_delivery')">待配送</div>
			<div class="tab" onclick="switchTab('pending_receipt')">待收货</div>
		</div>

		<!-- 		订单列表
		<div class="order-card">
			<div class="order-header">
				<div class="order-shop">川味小厨</div>
				<div class="order-status">已完成</div>
			</div>
			<div class="order-time">2023-05-15 12:30</div>
			<div class="order-item">
				<div class="item-name">水煮鱼 x1</div>
				<div class="item-price">¥38</div>
			</div>
			<div class="order-item">
				<div class="item-name">夫妻肺片 x1</div>
				<div class="item-price">¥28</div>
			</div>
			<div class="order-total">
				<div>共2件商品</div>
				<div>实付: ¥66</div>
			</div>
			<div class="order-actions">
				<div class="action-btn">再来一单</div>
				<div class="action-btn">评价</div>
			</div>
		</div>

		<div class="order-card">
			<div class="order-header">
				<div class="order-shop">老北京炸酱面</div>
				<div class="order-status">配送中</div>
			</div>
			<div class="order-time">2023-05-16 18:15</div>
			<div class="order-item">
				<div class="item-name">炸酱面 x2</div>
				<div class="item-price">¥30</div>
			</div>
			<div class="order-total">
				<div>共1件商品</div>
				<div>实付: ¥32</div>
			</div>
			<div class="order-actions">
				<div class="action-btn primary-btn">确认收货</div>
				<div class="action-btn">联系商家</div>
			</div>
		</div> -->

		<!-- 底部导航 -->
		<div class="bottom-nav">
			<div class="nav-item active" onclick="goToHome()">
				<div class="nav-icon">🏠</div>
				<div>首页</div>
			</div>
			<div class="nav-item" onclick="goToOrders()">
				<div class="nav-icon">📦</div>
				<div>订单</div>
			</div>
			<div class="nav-item" onclick="goToCart()">
				<div class="nav-icon">🛒</div>
				<div>购物车</div>
			</div>
			<div class="nav-item" onclick="goToProfile()">
				<div class="nav-icon">👤</div>
				<div>我的</div>
			</div>
		</div>
	</body>
</html>
<script>
	$(function() {
		// 页面加载时获取订单列表
		getOrdersList();
	})

	function goToHome() {
		window.location.href = "home.html"
	}

	function goToCart() {
		window.location.href = "cart.html"
	}

	function goToProfile() {
		window.location.href = "profile.html"
	}

	function goBack() {
		window.history.back();
	}

	function switchTab(tabType) {
		// 切换标签样式
		$('.order-tabs .tab').removeClass('active');
		$(`.order-tabs .tab[onclick*="${tabType}"]`).addClass('active');

		// 根据标签类型筛选订单
		getOrdersList(tabType);
	}

	function getOrdersList(status = 'all') {
		const token = sessionStorage.getItem('token');
		if (!token) {
			window.location.href = 'login.html';
			return;
		}

		$.ajax({
			url: 'http://localhost:8080/orders',
			type: 'GET',
			contentType: 'application/json',
			dataType: 'json',
			headers: {
				Authorization: 'Bearer' + sessionStorage.getItem("token")
			},
			data: {
				status: status
			},
			success: function(response) {
				console.log('订单数据:', response);
				if (response.code === 1 && response.data) {
					// 清空现有订单列表
					$('.order-card').remove();

					// 创建订单容器
					const ordersContainer = $('<div class="orders-container"></div>');
					$('body').append(ordersContainer);

					// 遍历订单数据并创建卡片
					response.data.forEach(order => {
						// 计算商品总数和总价
						const totalItems = order.items.reduce((sum, item) => sum + item.quantity, 0);
						const totalPrice = order.items.reduce((sum, item) => sum + (item.price * item
							.quantity), 0) + order.deliveryFee;

						// 创建订单项HTML
						const itemsHtml = order.items.map(item => `
                            <div class="order-item">
                                <div class="item-name">${item.name} x${item.quantity}</div>
                                <div class="item-price">¥${item.price.toFixed(2)}</div>
                            </div>
                        `).join('');

						// 根据订单状态确定操作按钮
						let actionsHtml = '';
						switch (order.status) {
							case 'pending_payment':
								actionsHtml = `
                                    <div class="action-btn primary-btn">去支付</div>
                                    <div class="action-btn">取消订单</div>
                                `;
								break;
							case 'pending_delivery':
								actionsHtml = `
                                    <div class="action-btn">联系商家</div>
                                    <div class="action-btn">取消订单</div>
                                `;
								break;
							case 'pending_receipt':
								actionsHtml = `
                                    <div class="action-btn primary-btn">确认收货</div>
                                    <div class="action-btn">联系骑手</div>
                                `;
								break;
							case 'completed':
								actionsHtml = `
                                    <div class="action-btn">再来一单</div>
                                    <div class="action-btn">评价</div>
                                `;
								break;
							default:
								actionsHtml = `
                                    <div class="action-btn">查看详情</div>
                                `;
						}

						// 创建订单卡片HTML
						const cardHtml = `
                            <div class="order-card">
                                <div class="order-header">
                                    <div class="order-shop">${order.shopName}</div>
                                    <div class="order-status ${order.status}">${getStatusText(order.status)}</div>
                                </div>
                                <div class="order-time">${formatTime(order.createTime)}</div>
                                ${itemsHtml}
                                <div class="order-total">
                                    <div>共${totalItems}件商品</div>
                                    <div>实付: ¥${totalPrice.toFixed(2)}</div>
                                </div>
                                <div class="order-actions">
                                    ${actionsHtml}
                                </div>
                            </div>
                        `;

						ordersContainer.append(cardHtml);
					});
				} else {
					console.error('获取订单列表失败:', response.message);
					// 显示空状态提示
					$('.orders-container').html('<div class="empty-orders">暂无订单数据</div>');
				}
			},
			error: function(xhr, status, error) {
				console.error('请求失败:', error);
				alert('获取订单列表失败，请稍后重试');
			}
		});
	}

	// 辅助函数：获取状态文本
	function getStatusText(status) {
		const statusMap = {
			'pending_payment': '待付款',
			'pending_delivery': '待配送',
			'pending_receipt': '待收货',
			'completed': '已完成',
			'cancelled': '已取消'
		};
		return statusMap[status] || status;
	}

	// 辅助函数：格式化时间
	function formatTime(timestamp) {
		const date = new Date(timestamp);
		return `${date.getFullYear()}-${padZero(date.getMonth()+1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}`;
	}

	function padZero(num) {
		return num < 10 ? `0${num}` : num;
	}
</script>
